package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"strings"
)

type Sentinel struct {
	masterName string
	masterIp   string
	masterPort string
}

var sentinelClient *redis.SentinelClient
var masterClient *redis.Client

func main() {
	se := RedisSentinel()
	GetMasterClient(se)

}

/*
获取sentienl 客户端
*/
func RedisSentinel() *redis.SentinelClient {
	//rdb := redis.NewFailoverClient(&redis.FailoverOptions{
	//	MasterName:    "mymaster",
	//	SentinelAddrs: []string{"127.0.0.1:26379","127.0.0.1:26480","127.0.0.1:26481"},
	//})
	if sentinelClient != nil {
		return sentinelClient
	}
	/**
	连接26379端口的sentinel；多个sentinel应循环获取可用的sentinel；
	这里简单实现
	*/
	sentinelClient = redis.NewSentinelClient(&redis.Options{
		Network: "tcp",
		Addr:    "180.76.234.135:26379",
	})

	//订阅切换主消息
	go subScribe(sentinelClient)

	return sentinelClient
}

//处理 切主操作
/**
这里随便 订阅一个sentinel的 +switch-master
切换master会 sentinel 会向+switch-master发布一个消息
*/
func subScribe(sentinelClient *redis.SentinelClient) {
	fmt.Println("ccc")
	pubsub := sentinelClient.Subscribe("+switch-master")
	fmt.Println("ddd")
	_, err := pubsub.Receive()
	if err != nil {
		return
	}
	ch := pubsub.Channel()
	for msg := range ch {
		fmt.Println("newMaster", msg.Channel, msg.Payload, "\r\n")
		master := strings.Split(msg.Payload, " ")
		fmt.Println(master)
		masterClient = redis.NewClient(&redis.Options{
			Network: "tcp",
			Addr:    master[1] + ":" + master[2],
		})
	}
}

/**
获取主节点信息
*/
func GetMasterClient(sentinelClient *redis.SentinelClient) *redis.Client {
	/*if masterClient !=nil {
		return masterClient
	}*/

	masterInfo, _ := sentinelClient.GetMasterAddrByName("mymaster").Result()

	fmt.Println("masterInfo", masterInfo)

	masterClient = redis.NewClient(&redis.Options{
		Network: "tcp",
		Addr:    masterInfo[0] + ":" + masterInfo[1],
	})
	fmt.Println("master", masterInfo[0]+masterInfo[1])
	return masterClient
}

func Subscribe() {
	client := redis.NewClient(&redis.Options{
		Network: "tcp",
		Addr:    "127.0.0.1:26379",
	})

	//参数1 频道名 字符串类型
	pubsub := client.Subscribe("+switch-master")
	_, err := pubsub.Receive()
	if err != nil {
		return
	}
	ch := pubsub.Channel()
	for msg := range ch {
		fmt.Println(msg.Channel, msg.Payload, "\r\n")
	}
}
